﻿using System;
using System.Drawing;

namespace QuadrantImageSlicer
{
    class Program
    {
        static void Main(string[] args)
        {
            var imagePath = System.Configuration.ConfigurationManager.AppSettings["image_uri"];

            if (!System.IO.File.Exists(imagePath))
                System.Console.WriteLine("Error: The image specified in the image_uri property in the App.config file does not exist.");

            var outputFolder = System.Configuration.ConfigurationManager.AppSettings["output_folder"];

            if (!System.IO.Directory.Exists(outputFolder))
                System.Console.WriteLine("Error: The folder specified in the output_folder property in the App.config file does not exist.");

            var imageNamePrefix = System.Configuration.ConfigurationManager.AppSettings["image_name_prefix"];

            System.Console.WriteLine("1. Loading image from " + imagePath);
            var image = Image.FromFile(imagePath);
            var tile = new Bitmap(128, 128);
            var index = 1;
            var columns = Math.Ceiling((double)image.Width / 128);
            var rows = Math.Ceiling((double)image.Height / 128);

            System.Console.WriteLine("2. Saving tiles to " + outputFolder);
            for (var r = 0; r < rows; r++)
            {
                for (var c = 0; c < columns; c++)
                {
                    using (var graphics = Graphics.FromImage(tile))
                    {
                        graphics.DrawImage(image, new Rectangle(0, 0, 128, 128), 128 * c, 128 * r, 128, 128, GraphicsUnit.Pixel);
                        tile.Save(string.Format("{0}{1}{2}.jpg", outputFolder, imageNamePrefix, index), System.Drawing.Imaging.ImageFormat.Jpeg);
                    }

                    index++;
                }
            }

            System.Console.WriteLine("3. Finished!");
        }
    }
}